package android.framework.rpc;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class HttpSender implements ISender<String>{

	private ServerDetails serverDetails;
	
	public String send(String data) throws IOException {
		
		
		 // Create a new HttpClient and Post Header
	    HttpClient httpclient = new DefaultHttpClient();
	    HttpPost httppost = new HttpPost(serverDetails.ServerAddress);

	    try {
	        // Add your data
	        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
	        nameValuePairs.add(new BasicNameValuePair("data", data));
	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

	        // Execute HTTP Post Request
	        HttpResponse response = httpclient.execute(httppost);
	        
	        return extractContent(response.getEntity());
	        
	    } catch (ClientProtocolException e) {
	        throw new IOException(e.getMessage());
	    }
	}

	
	private String extractContent(HttpEntity httpEntity) throws IllegalStateException, IOException{
		StringBuilder result = new StringBuilder();
		int contentLength = (int)httpEntity.getContentLength();
		byte[] buffer = new byte[contentLength];
		int byteRemains = contentLength;
		while(byteRemains > 0){
			int read = httpEntity.getContent().read(buffer);
			result.append(new String(buffer));
			byteRemains-=read;
		}
		return result.toString();
	}
	
	public void init(ServerDetails serverDetails) {
		this.serverDetails = serverDetails;
	}

}
